package com.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pojo.Consumption;
import com.pojo.Taocan;
import com.pojo.User;
import com.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Random;

@Controller
public class UserController {
    // 定义日志记录器
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public String register(@RequestParam("cardNumber") int cardNumber,
                           @RequestParam("package") int packageId,
                           @RequestParam("username") String username,
                           @RequestParam("password") String password,
                           @RequestParam("prepaid") double prepaid,
                           ModelMap model) {
        // 生成随机卡号
        List<String> cardNumbers = generateCardNumbers();
        String selectedCardNumber = cardNumbers.get(cardNumber - 1);

        // 获取套餐信息
        List<Taocan> packages = getPackages();
        Taocan selectedPackage = packages.get(packageId - 1);

        // 检查预存话费是否足够
        if (prepaid < selectedPackage.getMoney()) {
            model.put("msg", "您预存的话费金额不足以支付本月固定套餐资费，请重新充值！");
            return "register"; // 返回注册页面
        }

        // 创建新用户
        User user = new User();
        user.setName(username);
        user.setMima(password);
        user.setNumber(selectedCardNumber);
        user.setHuafei(prepaid);
        user.setTaocan(selectedPackage.getId());

        try {
            // 保存用户信息到数据库
            userService.register(user);
            model.put("msg", "注册成功！");
            return "menu"; // 返回菜单页面
        } catch (Exception e) {
            logger.error("用户注册失败", e); // 使用日志记录错误
            model.put("msg", "注册失败，请稍后重试。");
            return "register"; // 返回注册页面
        }
    }
    //生成随即卡号
    private List<String> generateCardNumbers(){
        List<String> cardNumbers = new ArrayList<String>();
        Random random = new Random();
        for (int i =0;i<9;i++){
            int randomNumber = 10000000 + random.nextInt(90000000);
            cardNumbers.add("139"+randomNumber);
        }
        return cardNumbers;
    }
    //获取套餐信息
    private List<Taocan> getPackages(){
        List<Taocan> packages = new ArrayList<Taocan>();
        Taocan package1 = new Taocan();
        package1.setId(1);
        package1.setTaocan_name("话唠套餐");
        package1.setMoney(58);
        packages.add(package1);

        Taocan package2 = new Taocan();
        package2.setId(2);
        package2.setTaocan_name("网虫套餐");
        package2.setMoney(68);
        packages.add(package2);

        Taocan package3 = new Taocan();
        package3.setId(3);
        package3.setTaocan_name("超人套餐");
        package3.setMoney(78);
        packages.add(package3);

        return packages;
    }
    @RequestMapping(value = "/login",method = {RequestMethod.GET,RequestMethod.POST})
    public String login(@Validated User user, BindingResult r, ModelMap m, HttpSession session){
        if (r.hasErrors()){
            List<ObjectError> errors = r.getAllErrors();
            for (ObjectError error:errors){
                System.out.println(error.getDefaultMessage());
            }
            m.put("msg","校验不合格 登录失败");
            m.put("errors",errors);
            return "login";//校验失败返回登录页
        }
        User userInfo = userService.login(user);
        if (userInfo!=null){
            session.setAttribute("number",userInfo.getNumber());
            m.put("msg","登录成功");
            logger.info("用户{}登录成功", userInfo.getNumber()); // 记录登录成功日志
            return "menu";
        }else {
            m.put("msg","卡号或密码错误");
            return "login";
        }
    }


    @RequestMapping(value = "/userToList",method = {RequestMethod.GET,RequestMethod.POST})
    public ModelAndView test1(@RequestParam(value = "pageNum",required = false)Integer pageNum,
                              @RequestParam(value = "pageSize",required = false)Integer pageSize){
        //当前第几页
        Integer num = 1;
        //每页多少条
        Integer size = 5;

        //判断是不是第一次进入页面
        if(pageNum!=null&&!"".equals(pageNum)){
            num = pageNum;
        }
        if(pageSize!=null&&!"".equals(pageSize)){
            size = pageSize;
        }

        //设置分页的初始化参数
        PageHelper.startPage(num,size);
        //获取数据列表
        List<User> list = userService.selectUserAll();
        //加载分页工具 加入数据源
        PageInfo<User> pagehelper = new PageInfo<User>(list);

        ModelAndView mav = new ModelAndView("userList","pagehelper",pagehelper);
        return mav;
    }
    @PostMapping("/chongzhi")
    public String recharge(@RequestParam("cardNumber") String cardNumber,
                           @RequestParam("rechargeAmount") double rechargeAmount,
                           ModelMap model) {
        // 验证充值金额是否最少 50 元
        if (rechargeAmount < 50) {
            model.put("msg", "充值金额最少为 50 元，请重新输入！");
            return "chongzhi";
        }

        // 根据卡号查找用户
        Optional<User> userOptional = userService.getUserByCardNumber(cardNumber);
        if (userOptional.isPresent()) {
            User user = userOptional.get();
            // 更新用户余额
            user.setHuafei(user.getHuafei() + rechargeAmount);
            userService.updateUser(user);
            model.put("msg", "充值成功！当前余额: " + user.getHuafei());
            logger.info("用户{}充值{}元成功", cardNumber, rechargeAmount); // 记录充值日志
        } else {
            model.put("msg", "未找到该卡号对应的用户，请检查卡号！");
            logger.warn("未找到卡号为{}的用户", cardNumber); // 记录警告日志
        }
        return "chongzhi";
    }
    @GetMapping("/tuichu")
    public String logout(HttpSession session) {
        // 清除会话中的用户信息
        session.invalidate();
        logger.info("用户退出登录"); // 记录退出日志

        // 跳转到退出页面
        return "logout";
    }

    @PostMapping("/useMobile")
    public String useMobile(@RequestParam("number") String number,
                            @RequestParam("mima") String mima,
                            Model model,
                            HttpServletRequest request) {
        try {
            logger.info("用户{}尝试消费", number); // 记录消费尝试日志
            // 登录验证
            User user = userService.loginByNumberAndPassword(number, mima);
            if (user == null) {
                model.addAttribute("error", "手机号或密码错误");
                return "login";
            }

            // 触发随机消费
            userService.triggerRandomConsumption(user);

            // 获取最新的用户信息和消费记录
            User updatedUser = userService.loginByNumberAndPassword(number, mima);
            List<Consumption> consumptionRecords = userService.getConsumptionRecords(user.getId());

            // 将数据添加到模型
            model.addAttribute("user", updatedUser);
            model.addAttribute("consumptions", consumptionRecords);
            model.addAttribute("success", "消费成功！");

            return "userDashboard";
        } catch (Exception e) {
            logger.error("消费过程发生异常", e); // 记录详细异常日志
            // 记录详细异常信息

            // 获取当前用户信息
            try {
                User user = userService.loginByNumberAndPassword(number, mima);
                if (user != null) {
                    model.addAttribute("user", user);
                    // 获取历史消费记录
                    List<Consumption> consumptionRecords = userService.getConsumptionRecords(user.getId());
                    model.addAttribute("consumptions", consumptionRecords);
                }
            } catch (Exception ex) {
                logger.error("获取用户信息失败", ex);
            }

            // 返回错误信息
            model.addAttribute("error", e.getMessage());

            // 保持在当前页面而不是重定向到登录页
            return "userDashboard";
        }
    }

    @PostMapping("/printRecord")
    public String printRecord(@RequestParam("number") String number, @RequestParam("mima") String mima, Model model) {
        User user = userService.loginByNumberAndPassword(number, mima);
        if (user != null) {
            List<Consumption> records = userService.getConsumptionRecords(user.getId());
            model.addAttribute("records", records);
            logger.info("用户{}查询消费记录", number); // 记录查询日志
        } else {
            model.addAttribute("msg", "卡号或密码错误");
            logger.warn("用户{}查询记录失败，卡号或密码错误", number); // 记录警告日志
        }
        return "print_record";
    }
}